package hr.pzrinscak.service;

import hr.pzrinscak.jpa.VacationRequest;
import hr.pzrinscak.util.StaticUtils;

import java.util.HashMap;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class JpaService {

    private final static Logger LOGGER = LoggerFactory.getLogger(JpaService.class);

    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    private RuntimeService runtimeService;

    @Transactional(propagation=Propagation.REQUIRED)
    public void saveVacationRequest(final VacationRequest vacationRequest, final String processDefinitionId) {
        
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        
        entityManager.persist(vacationRequest);

        Map<String,Object> variables = new HashMap<String, Object>();
        variables.put("package", vacationRequest);
        variables.put(StaticUtils.VARIABLE_ASSIGNED_BY, authentication.getName());
        
        ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinitionId, variables);
    }

}
